package cn.genmer.test.security.netty.io;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  使用需要在cmd窗口 输入telent 127.0.0.1 6666
 */
public class BIO {
    public static void main(String[] args) throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");
        while (true){
            // 监听，等待客户端连接
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接");

            // 创建一个线程，与客户端通讯
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.println("客户端通信中！");
                    System.out.println("当前连接线程id为:" + Thread.currentThread().getId());
                    handle(socket);
                }
            });
        }

    }
    public static void handle(Socket scoket){
        try {
            byte[] bytes = new byte[1024];
            // 获取数据流
            InputStream inputStream = scoket.getInputStream();

            while (true){
                int read = inputStream.read(bytes);
                if (read != -1){
                    System.out.println(new String(bytes,0,read));
                } else {
                    break;
                }

            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                scoket.close();
            } catch (Exception e){
                System.out.println("关闭异常！");
            }
        }
    }
}
